package com.example.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot.common.Constants;
import com.example.springboot.entity.Dict;
import com.example.springboot.service.IDictService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import com.example.springboot.utils.AjaxResult;
import com.example.springboot.service.IMenuService;
import com.example.springboot.entity.Menu;
import com.example.springboot.entity.User;
import com.example.springboot.utils.TokenUtils;
import java.util.ArrayList;

import java.util.List;
import cn.hutool.core.date.DateUtil;
import org.springframework.web.multipart.MultipartFile;
import com.example.springboot.utils.PageData;
import java.util.HashMap;
import java.util.Map;
import java.io.InputStream;
import java.net.URLEncoder;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.springframework.web.bind.annotation.RestController;
import org.yaml.snakeyaml.scanner.Constant;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cpf
 *
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Resource
    private IMenuService menuService;
    @Resource
    private IDictService dictService;


    // 新增或者更新
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public AjaxResult save(@RequestBody Menu menu) {
        try{
            Menu menuData = menuService.queryById(menu.getId());
            if(menuData == null){
                //save
                menuService.insert(menu);
                return AjaxResult.success("添加成功！");
            }else{
                menuService.update(menu);
                return AjaxResult.success("修改成功！");
            }
            //if (menu.getId() == null) {
            //menu.setTime(DateUtil.now());
            //menu.setUser(TokenUtils.getCurrentUser().getUsername());
            //}


        }catch(Exception e){
            e.printStackTrace();
            return AjaxResult.failure("请查看日志");
        }

    }
    @RequestMapping(value = "/{id}",method = RequestMethod.POST)
    public AjaxResult delete(@PathVariable Integer id) {
        try{
            List<Integer> ids = new ArrayList<>();
            ids.add(id);
            menuService.deleteByIds(ids);
            return AjaxResult.success("删除成功");
        }catch(Exception e){
            e.printStackTrace();
            return AjaxResult.failure("请查看日志");
        }
    }

    @RequestMapping(value = "/del/batch",method = RequestMethod.POST)
    public AjaxResult deleteBatch(@RequestBody List<Integer> ids) {
        try{
            menuService.deleteByIds(ids);
            return AjaxResult.success("删除成功！");
        }catch(Exception e){
            e.printStackTrace();
            return AjaxResult.failure("请查看日志");
        }
    }

    @RequestMapping(value = "/findAll",method = RequestMethod.GET)
    public AjaxResult findAll() {
        try{
            Map<String,Object> param = new HashMap<>();
            List<Menu> menuList = menuService.queryAllInfo(param);
            return AjaxResult.success("查询成功",menuList);
        }catch(Exception e){
            e.printStackTrace();
            return AjaxResult.failure("请查看日志");
        }
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public AjaxResult findOne(@RequestParam("id") Integer id) {
        try{
            Menu menu = menuService.queryById(id);
            return AjaxResult.success("查询成功",menu);
        }catch(Exception e){
            e.printStackTrace();
            return AjaxResult.failure("请查看日志");
        }
    }

    @RequestMapping(value = "/page",method = RequestMethod.POST)
    public AjaxResult findPage(@RequestBody Map<String,Object> param) {
        try{

            //User currentUser = TokenUtils.getCurrentUser();
            //if (currentUser.getRole().equals("ROLE_USER")) {
                //queryWrapper.eq("user", currentUser.getUsername());
            //}
            int pageSize = Integer.parseInt(String.valueOf(param.get("pageSize")));
            int page = Integer.parseInt(String.valueOf(param.get("page")));
            int startIndex = (page - 1) * pageSize;
            param.put("pageIndex",startIndex);
            long count = menuService.count(param);
            List<Menu> menuList = menuService.queryAllInfo(param);
            PageData pageData = new PageData(page, pageSize, menuList, count);
            return AjaxResult.success("查询成功！",pageData);
        }catch(Exception e){
            e.printStackTrace();
            return AjaxResult.failure("请查看日志");
        }
    }

    /**
    * 导出接口
    */
    @RequestMapping(value = "/export",method = RequestMethod.GET)
    public void export(HttpServletResponse response) throws Exception {
        try{
            // 从数据库查询出所有的数据,查询条件为空
            Map<String,Object> param = new HashMap<>();
            List<Menu> list = menuService.queryAllInfo(param);
            // 在内存操作，写出到浏览器
            ExcelWriter writer = ExcelUtil.getWriter(true);

            // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
            writer.write(list, true);

            // 设置浏览器响应的格式
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            String fileName = URLEncoder.encode("Menu信息表", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

            ServletOutputStream out = response.getOutputStream();
            writer.flush(out, true);
            out.close();
            writer.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * excel 导入
     * @param file
     * @throws Exception
     */
    @RequestMapping(value = "/import",method = RequestMethod.POST)
    public AjaxResult importFile(MultipartFile file) throws Exception {
        try{
            InputStream inputStream = file.getInputStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream);
            // 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
            List<Menu> list = reader.readAll(Menu.class);

            menuService.insertBatch(list);
            return AjaxResult.success("导入成功");
        }catch(Exception e){
            e.printStackTrace();
            return AjaxResult.failure("请查看日志");
        }
    }

    @RequestMapping(value = "/icons",method = RequestMethod.GET)
    public AjaxResult getIcons() {
        try {
            Map<String,Object> param = new HashMap<>();
            param.put("type", Constants.DICT_TYPE_ICON);
            List<Dict> dictList = dictService.queryAllInfo(param);
            return AjaxResult.success("查询成功",dictList);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.failure("请查看日志");
        }
    }

    @GetMapping("/ids")
    public AjaxResult findAllIds() {
        List<Integer> ids = menuService.queryAllIds();
        return AjaxResult.success("查询成功",ids);
    }

}

